<template>


    <div style="display:flex;flex-direction:column;justify-content:center;align-items:center;">

        <el-card class="info-card">
            <template #header>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>编辑课程</div>
                    <el-button type="primary" round size="large" @click="$router.back()">返回</el-button>
                </div>
            </template>

            <div style="display: flex;flex-direction: column; align-items: center; ">

                <div style="display: flex; flex-direction: column; align-items: center; margin-bottom:40px">
                    <UploadCover v-model="form.cover" />
                </div>


                <div style="display: flex; flex-direction: column; align-items: center;">

                    <div class="info_row">
                        <div class="info_row_left">班课名称：</div>
                        <div class="info_row_right">
                            <el-input size="large" maxlength="30" show-word-limit v-model="form.className"
                                placeholder="请输入班级名称" @input="debouncedSearchClass" />
                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">授课课程：</div>
                        <div class="info_row_right">
                            <el-input size="large" maxlength="30" show-word-limit v-model="form.teachingCourseName"
                                placeholder="请输入课程名称" @input="debouncedSearchCourse" />
                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">开课学期：</div>
                        <div class="info_row_right">
                            <el-select size="large" v-model="form.term" placeholder="请选择开课学期">
                                <el-option v-for="option in termOptions" :key="option.value" :label="option.label"
                                    :value="option.value"></el-option>
                            </el-select>
                        </div>
                    </div>


                    <div class="info_row">
                        <div class="info_row_left">课程描述：</div>
                        <div class="info_row_right">
                            <el-input size="large" maxlength="255" show-word-limit type="textarea"
                                v-model="form.description" placeholder="请输入课程描述" @input="debouncedSearchClass" />

                        </div>
                    </div>


                    <div class="info_row">
                        <div class="info_row_left">结束时间：</div>
                        <div class="info_row_right">
                            <el-date-picker type="datetime" placeholder="选择结束时间" size="default" clearable
                                v-model="form.end_time" @change="handleEndTimeChange" />
                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">作业权重：</div>
                        <div class="info_row_right">
                            <el-input-number :min="0" :max="100" :step="1" :step-strictly="true"
                                v-model.number="form.homework_weight" />

                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">实验权重：</div>
                        <div class="info_row_right">
                            <el-input-number :min="0" :max="100" :step="1" :step-strictly="true"
                                v-model.number="form.experiment_weight" />

                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">考试权重：</div>
                        <div class="info_row_right">
                            <el-input-number :min="0" :max="100" :step="1" :step-strictly="true"
                                v-model.number="form.exam_weight" />

                        </div>
                    </div>



                </div>
            </div>

            <div>
                <el-button size="large" type="primary" @click="handelEditCourse"
                    style="margin-top: 20px;">保存</el-button>
                <el-button size="large" type="primary" @click="$router.back()" style="margin-top: 20px;">取消</el-button>
            </div>
        </el-card>
    </div>


</template>

<script lang="ts" setup>
import {  ref, onMounted } from 'vue'
import UploadCover from './uploadCover.vue'

import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { searchClassNamesApi, searchCourseNamesApi,  editCourseApi } from '@/api/course'
import { debounce } from 'lodash';

const store = useStore()
const router = useRouter()

const form = ref({
    className: '',
    course_id: '',
    cover: null,
    description: '',
    end_time: '',
    status: '',
    teachingCourseName: '',
    term: '',
    user_id: store.state.user.user_id,
    homework_weight: 0,
    experiment_weight: 0,
    exam_weight: 0,
});
const termOptions = ref([]);
const classOptions = ref([]);
const courseOptions = ref([]);

onMounted(() => {
    const currentYear = new Date().getFullYear();
    const currentMonth = new Date().getMonth() + 1;
    const options = [];
    // Determine the current term
    const currentTerm = currentMonth >= 9 ? 1 : 2;
    const currentAcademicYear = currentTerm === 1 ? `${currentYear}-${currentYear + 1}` : `${currentYear - 1}-${currentYear}`;
    // Generate options for the current and next 4 academic years
    for (let i = 0; i < 2; i++) {
        const year = currentYear + i - 1;
        options.push({ label: `${year}-${year + 1} 第一学期`, value: `${year}-${year + 1} 第一学期` });
        options.push({ label: `${year}-${year + 1} 第二学期`, value: `${year}-${year + 1} 第二学期` });
    }
    termOptions.value = options;

    form.value.term = history.state.term;
    form.value.className = history.state.title;
    form.value.cover = history.state.cover;
    form.value.teachingCourseName = history.state.teachingCourseName;
    form.value.description = history.state.description;
    form.value.end_time = history.state.end_time;
    form.value.status = history.state.status;
    form.value.course_id = history.state.course_id;
    form.value.homework_weight = history.state.homework_weight;
    form.value.experiment_weight = history.state.experiment_weight;
    form.value.exam_weight = history.state.exam_weight;
});
const handleEndTimeChange = (date: any) => {
    form.value.end_time = date;
}
// 输入之后，延迟1秒查询班级
const debouncedSearchClass = debounce(() => {
    if (form.value.className.trim() === '') {
        classOptions.value = [];
        return;
    }
    try {
        searchClassNamesApi({ cls_name: form.value.className }).then((res) => {
            classOptions.value = res.data;
        });
    } catch (error) {
        console.error('Error searching class:', error);
    }
}, 1500)

const debouncedSearchCourse = debounce(() => {
    if (form.value.className.trim() === '') {
        classOptions.value = [];
        return;
    }
    try {
        searchCourseNamesApi({ course_name: form.value.teachingCourseName }).then((res) => {
            courseOptions.value = res.data;
        });
    } catch (error) {
        console.error('Error searching class:', error);
    }
}, 1500);

const handelEditCourse = () => {
    if (form.value.className.trim() === '') {
        ElMessage.error('班课名称不能为空');
        return;
    }
    if (form.value.teachingCourseName.trim() === '') {
        ElMessage.error('授课课程名称不能为空');
        return;
    }
    if (form.value.term.trim() === '') {
        ElMessage.error('开课学期不能为空');
        return;
    }
    const totalWeight = form.value.homework_weight + form.value.experiment_weight + form.value.exam_weight;
    if (totalWeight !== 100) {
        ElMessage.error('总权重必须为100%');
        return;
    }
    try {
        editCourseApi(form.value).then((res: any) => {
            if (res.code === 200) {
                ElMessage.success('编辑课程成功');
                router.back();
            } else {
                ElMessage.error('编辑课程失败');
            }
        });
    } catch (error) {
        console.error('Error editing course:', error);
    }
};

</script>

<style lang="scss" scoped>
.info-card {
    position: relative;
    width: 100vw;
    max-width: 1200px;
    height: auto;
    // max-height: 600px;///

    align-content: center;
    margin-top: 10px;
}



.info_row {
    display: flex;
    justify-content: space-between;
    // width: 600px;
    margin-bottom: 30px;
    vertical-align: auto;
    align-self: center;
}

.info_row_left {
    width: 10vw;
    min-width: 100px;
    text-align: left;
    font-size: large;
}

.info_row_right {
    width: 20vw;
    min-width: 200px;
    text-align: left;
    font-size: large;

}
</style>